package io.feige.rpc.consumer.config;

import io.feige.rpc.consumer.RpcConsumerService;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RemoteServiceConfigManager {

	protected static final long CONFIG_UPDATE_TIME = 20000;

	private static Logger logger=LoggerFactory.getLogger(RemoteServiceConfigManager.class);
	
	private Map<String, RemoteServiceConfig> remoteServiceConfigMap=new ConcurrentHashMap<String, RemoteServiceConfig>();
	
	private RpcConsumerService rpcConsumerService;
	
	private volatile boolean stop;
	
	public RemoteServiceConfigManager(RpcConsumerService rpcConsumerService){
		this.rpcConsumerService=rpcConsumerService;
	}
	
	public void init(List<RemoteServiceConfig> configs){
		for (RemoteServiceConfig remoteServiceConfig : configs) {
			remoteServiceConfigMap.put(remoteServiceConfig.getService(), remoteServiceConfig);
		}
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				synchronized (this) {
					try {
						while(!stop){
							wait(CONFIG_UPDATE_TIME);
							try {
								logger.debug("sync configs and update connections"); 
								updateConnections();
							} catch (Exception e) {
								logger.warn("error", e);
							}
						}
					} catch (InterruptedException e) {
						logger.warn("config update thread exit");
					}
				}
			}
		}).start();
	}
	 
	
	public RemoteServiceConfig getrRemoteServiceConfig(String service){
		return remoteServiceConfigMap.get(service);
	}
	
	public Map<String, RemoteServiceConfig> getRemoteServiceConfigMap() {
		return remoteServiceConfigMap;
	}
	
	public void destroy(){
		stop=true;
	}
	
	private void updateConnections(){
		rpcConsumerService.getConnectionService().updateConnections(remoteServiceConfigMap);
	}
	
	
}
